package com.tianji.learning.mq;

import cn.hutool.core.util.ObjectUtil;
import com.tianji.api.client.course.CourseClient;
import com.tianji.api.dto.course.CourseSearchDTO;
import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.learning.domain.po.LearningLesson;
import com.tianji.learning.service.ILearningService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * TODO
 *
 * @Author whx
 * @Date 2024/11/23 16:48
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class OrderEventListener {

    private final ILearningService learningService;

    private final CourseClient courseClient;

    /**
     * 免费报名成功插入课程到我的课表
     * @param obj
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.ADD_LESSON_2_COURSE, durable = "true"),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_PAY_KEY
    ))
    public void addLesson2Course(Object obj){
        log.info("mq接收到免费报名成功的消息！！！");
        // 接收到报名成功的消息
        // 将课程添加到课表中
        OrderBasicDTO orderBasicDTO = (OrderBasicDTO) obj;

        // 封装LearningLesson对象插入数据库
        List<LearningLesson> learningLessons = new ArrayList<>();
        Long userId = orderBasicDTO.getUserId();

        for (Long courseId : orderBasicDTO.getCourseIds()) {
            // 获取过期时间
            CourseSearchDTO searchInfo = courseClient.getSearchInfo(courseId);
            LocalDateTime expireTime = orderBasicDTO.getFinishTime().plusMonths(searchInfo.getDuration());

            // 封装信息
            LearningLesson lesson = new LearningLesson().builder()
                    .createTime(LocalDateTime.now())
                    .updateTime(LocalDateTime.now())
                    .userId(userId)
                    .courseId(courseId)
                    .status(0)
                    .planStatus(0)
                    .expireTime(expireTime)
                    .build();

            learningLessons.add(lesson);
        }

        // 批量插入免费课程到课表
        learningService.saveBatch(learningLessons);
    }

    /**
     * 退款 从课表删除课程
     * @param obj
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queue.REMOVE_COURSE_QUEUE),
            exchange = @Exchange(name = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
            key = MqConstants.Key.ORDER_REFUND_KEY
    ))
    public void removeCourseAfterRefund(Object obj){
        log.info("mq接收到退款删除课程信息！！！");
        OrderBasicDTO orderBasicDTO = (OrderBasicDTO) obj;

        if(ObjectUtil.isEmpty(orderBasicDTO)){
           return;
        }
//        Long orderId = orderBasicDTO.getOrderId();
        Long userId = orderBasicDTO.getUserId();
        for (Long courseId : orderBasicDTO.getCourseIds()) {

            // 根据orderId，userId，courseId删除指定课表
            learningService.lambdaUpdate()
                    .eq(LearningLesson::getCourseId, courseId)
                    .eq(LearningLesson::getUserId, userId)
                    .remove();
        }
    }
}
